<?php defined('SYSPATH') or die('No direct access allowed.');

class Controller_Admin_News extends Controller_Admin_Template
{
    
    public function after()    
    {
        
        $this->template->styles = array('css/admin/fileuploader.css' => 'screen');
        $this->template->scripts = array('js/fileuploader.js');
        
        parent::after();
    }
    
    
    public function action_index()
    {                                      
  	$count = DB::query(Database::SELECT, "SELECT COUNT(*) as `count` FROM `news`")
                    ->execute()
                    ->get('count');
        
  	$pagination = Pagination::factory(array('total_items' => $count));
        
        $news = DB::query(Database::SELECT, "SELECT * FROM `news`
                                            ORDER BY `modified` DESC
                                            LIMIT :offset, :limit")
                        ->param(':offset', $pagination->offset)
                        ->param(':limit', $pagination->items_per_page)
                        ->as_object()
                        ->execute();                
              
  	$page_links = $pagination->render(); 
        
        $this->template->content = View::factory('admin/news/news')
                                       ->set('news', $news)
                                       ->set('page_links', $page_links);
        
    }
    
    public function action_add()
    {
                
        $this->template->content = View::factory('admin/news/form')
                                        ->set('title', 'Добавление новости')
                                        ->set('news', array());                                       
    }
    
    public function action_edit()
    {
        $id = Arr::get($_REQUEST, 'id', -1);       

        $news = ORM::factory('news', $id);
        if($news->loaded()){           
            $news = $news->as_array();
        
            $this->template->content = View::factory('admin/news/form')     
                                           ->set('title', 'Редактирование новости')
                                           ->set('news', $news);
                                           
        } else        
            Request::$initial->redirect('admin/news');
    }
    
    public function action_save()
    {
        $this->auto_render = false;
        
        $id = Arr::get($_POST, 'id', '');
        
        if(!empty($id)){
            $news = ORM::factory('news', $id)
                        ->values($_POST)
                        ->set('modified', DB::expr('NOW()'));            
            
        } else {
            $news = ORM::factory('news')
                            ->values($_POST)
                            ->set('created', DB::expr('NOW()'))
                            ->set('modified', DB::expr('NOW()'));
        }
        
        try
        {            
            $news->save();
            
             if(empty($id)){
                 DB::query(Database::UPDATE, "UPDATE `news_images` SET `news_id`=:news_id WHERE `news_id` IS NULL")
                    ->param(':news_id', $news->pk())
                    ->execute();
             }
            
            $response = array('status' => 'ok');
        }
        catch(Kohana_ORM_Validation_Exception $e)
        {
            $errors = $e->errors('/admin');
            $response = array('status' => 'error',
                              'error' => $errors);
        }
     
        $this->response->body(json_encode($response));        
    }
    
    public function action_del()
    {
        $id = Arr::get($_GET, 'id', 0);
        try
        {
            ORM::factory('news', $id)->delete();
        }
        catch(Exception $e){}
        
        Request::$initial->redirect(Request::$initial->referrer());
    }
    
     public function action_images()
    {
        $this->auto_render = false;
        
        $id = Arr::get($_REQUEST, 'id', 0);       
        $response = array();
        if($id)
            $files = DB::query(Database::SELECT, "SELECT `file` FROM `news_images` WHERE `news_id`=$id")
                            ->execute();
        else
            $files = DB::query(Database::SELECT, "SELECT `file` FROM `news_images` WHERE `news_id` IS NULL")
                            ->execute();
        
        foreach($files as $file){
            $path = Kohana::$config->load('news')->get('image_path');
            $src = $path.$file['file'];
            $response[] = str_replace('.', '_min.', $src);
        }
        
        $this->response->body(json_encode($response));       
        
    }
    
    public function action_image_delete()
    {
        $this->auto_render = false;
        
        if(Request::$initial->is_ajax()){
	    $src = Arr::get($_POST, 'src', '');
	    if(!empty($src)){
                $targetFile = '.'.$src;
		unlink($targetFile);

		$targetFile = str_replace('_min', '', $targetFile);
		unlink($targetFile);
                
                $pathinfo = pathinfo(str_replace('_min', '', $src));
                $file = $pathinfo['filename'].'.'.$pathinfo['extension'];
                DB::query(Database::DELETE, "DELETE FROM `news_images` WHERE `file`=:file LIMIT 1")
                        ->param(':file', $file)
                        ->execute();
	    }
	}
    }
    
     public function action_image_upload()
     {
        $this->auto_render = false;
        
        $news_config = Kohana::$config->load('news');
        
        $allowedExtensions = array();
        $sizeLimit = 2 * 1024 * 1024;

        $uploader = new qqFileUploader($allowedExtensions, $sizeLimit);      
        
        $result = $uploader->handleUpload('.'.$news_config->get('image_path'));
        
        
        if($result['success']){            
            $image = Image::factory($result['filename']);	    
            $width = $news_config->get('image_min_width');
	    $height = $news_config->get('image_min_height');
	    $wh = $width / $height;
	    $image_wh = $image->width / $image->height;
	    if($wh > $image_wh)
		$image->crop($image->width, $image->width / $wh);
	    else
		$image->crop($image->height * $wh, $image->height);
	    $image->resize($width);
	    
	    $ext = pathinfo($result['filename'], PATHINFO_EXTENSION);            
            $targetFile =  str_replace(".$ext", "_min.$ext", $result['filename']);
	    $image->save($targetFile);
            
            /*
            $image = Image::factory($result['filename']); 
            $mark = Image::factory('./images/watermark.png');

            $mark_per_x = floor($image->width / $mark->width);
            $mark_per_y = floor($image->height / $mark->height);

            $start_x = round(($image->width - $mark_per_x*$mark->width) / 2);
            $start_y = round(($image->height - $mark_per_y*$mark->height) / 2);

            for($x = 0; $x < $mark_per_x; $x++)
                for($y = 0; $y < $mark_per_y; $y++)
                    $image->watermark($mark, $start_x + $x*$mark->width, $start_y + $y*$mark->height);

            $image->save();
            */
            
            $id = (Arr::get($_GET, 'id', 0)) ? $_GET['id'] : NULL;
    
            $pathinfo = pathinfo($result['filename']);
            $file = $pathinfo['filename'].'.'.$pathinfo['extension'];
            
            
            DB::query(Database::INSERT, "INSERT INTO `news_images` VALUES(NULL, :news_id,  NULL, :file)")
               ->param(':news_id', $id)
               ->param(':file', $file)
               ->execute();  
       }

       $this->response->body(htmlspecialchars(json_encode($result), ENT_NOQUOTES));
        
    }
}